import shortid from 'shortid'
// const lowdb = require('../lowdb/lowdb')
import lowdb from '../lowdb/lowdb'

const dateutil = require('../util/util')

// 查询资源列表
function queryList (item) {
  return lowdb.get('resources').find({ name: item.name, tag: item.tag }).value()
}

// 添加资源
function addItem (item) {
  let resource = lowdb.get('resources').find({ name: item.name, tag: item.tag }).value()
  let children = []
  if (resource === undefined) {
    lowdb.get('resources').push({
      id: shortid.generate(),
      name: item.name,
      tag: item.tag,
      children: []
    }).write()
  } else {
    children = resource.children
  }
  children.push({
    address: item.address,
    ip: item.ip,
    user: item.user,
    pwd: item.pwd,
    date: dateutil.dateFormat('YYYY-mm-dd HH:MM:SS', new Date()),
    desc: item.desc
  })
  lowdb.get('resources').find({ name: item.name, tag: item.tag }).assign({
    children: children
  }).write()
}

// 删除资源项目
function delItem (item, resource) {
  let childrens = lowdb.get('resources').find({name: item.name}).value().children
  childrens.forEach((e, index) => {
    if (e.address === resource.address) { // 删除源标签
      childrens.splice(index, 1)
    }
  })
  // childrens.push({ label: item.tag }) // 添加新标签
  lowdb.get('resources').find({ name: item.name }).assign({
    children: childrens
  }).write()
  // lowdb.get('resources').remove({ id: item.id }).write()
}

export { queryList, addItem, delItem }
